package com.ruoyi.carton.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.carton.domain.*;
import com.ruoyi.carton.domain.bo.OrderInboundBO;
import com.ruoyi.carton.domain.vo.OrderInboundListVO;
import com.ruoyi.carton.domain.vo.OrderInboundUpdateVO;
import com.ruoyi.carton.mapper.OrderInboundMapper;
import com.ruoyi.carton.service.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author 时空
* @description 针对表【order_inbound(纸板入库单)】的数据库操作Service实现
* @createDate 2025-06-30 14:27:54
*/
@Service
public class OrderInboundServiceImpl extends ServiceImpl<OrderInboundMapper, OrderInbound>
    implements OrderInboundService{

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private BoxService boxService;
    @Autowired
    private OrderRequestService orderRequestService;

    @Autowired
    private CardboardService cardboardService;

    @Override
    public void createInboundReceipt(Orders order) {
        if (order == null || order.getId() == null) {
            throw new IllegalArgumentException("订单信息不能为空");
        }
        // 1. 根据 orderId 查询 OrderRequest 记录
        LambdaQueryWrapper<OrderRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderRequest::getOrderId, order.getId());
        OrderRequest orderRequest = orderRequestService.getOne(queryWrapper);

        if (orderRequest == null) {
            throw new RuntimeException("未找到对应的请购单");
        }
        //判断请购单对应纸板是否存在
        if (orderRequest.getCardboardId() == null) {
            throw new RuntimeException("请购单对应的纸板不存在");
        }

        // 2. 构建 OrderInbound 实体并设置属性
        OrderInbound orderInbound = new OrderInbound();
        orderInbound.setOrderId(order.getId());
        orderInbound.setCardboardId(orderRequest.getCardboardId());
        orderInbound.setCreateTime(LocalDateTime.now());

        // 3. 保存入库单
        this.save(orderInbound);
    }

    @Override
    public OrderInboundBO getInboundById(Integer id) {
        // 查询入库单
        OrderInbound inbound = this.getById(id);
        if (inbound == null) {
            throw new ServiceException("入库单不存在");
        }
        OrderInboundBO bo = new OrderInboundBO();
        BeanUtils.copyProperties(inbound, bo);
        // 查询 Orders
        Orders order = ordersService.getById(inbound.getOrderId());
        if (order != null) {
            bo.setCustomerName(order.getCustomerName());

            // 查询 Box 获取 productName
            if (StringUtils.isNotEmpty(order.getProductId())) {
                Box box = boxService.getById(order.getProductId());
                if (box != null) {
                    bo.setProductName(box.getProductName());
                }
            }
        }
        // 查询 Cardboard 获取详细规格
        if (StringUtils.isNotEmpty(inbound.getCardboardId())) {
            Cardboard cardboard = cardboardService.getById(inbound.getCardboardId());
            if (cardboard != null) {
                bo.setSizeLength(cardboard.getSizeLength());
                bo.setSizeWidth(cardboard.getSizeWidth());
                bo.setUnitPrice(cardboard.getUnitPrice());
                bo.setFluteType(cardboard.getFluteType());
            }
        }
        return bo;
    }

    @Override
    public List<OrderInboundBO> selectBOList(OrderInboundListVO queryVO) {
        return baseMapper.selectBOList(queryVO.getOrderId(), queryVO.getProductName());
    }

    @Override
    public boolean  deleteInboundById(Integer id) {
        // 1. 查询入库单
        OrderInbound inbound = this.getById(id);
        if (inbound == null) {
            throw new RuntimeException("入库单不存在");
        }

        // 2. 查询对应订单
        Orders order = ordersService.getById(inbound.getOrderId());
        if (order == null) {
            throw new RuntimeException("对应订单不存在");
        }

        // 3. 校验订单当前状态为 IN_STOCK
        if (order.getStatus() != OrderStatus.IN_STOCK) {
            throw new RuntimeException("当前订单状态不是【入库】，无法删除入库单");
        }

        // 4. 删除入库单
        boolean deleted = this.removeById(id);
        if (!deleted) {
            throw new RuntimeException("删除入库单失败");
        }

        // 5. 状态回退为 REQUESTED（请购）
        order.setStatus(OrderStatus.REQUESTED);
        ordersService.updateById(order);

        // 6. 删除 cardboard 数据（如有需求）
//        cardboardService.removeById(inbound.getCardboardId());

        return true;
    }

    @Override
    public boolean updateOrderInboundById(OrderInboundUpdateVO vo) {
        if (vo.getId() == null) {
            throw new IllegalArgumentException("入库单 ID 不能为空");
        }

        OrderInbound existing = this.getById(vo.getId());
        if (existing == null) {
            return false;
        }
        // 更新允许修改的字段
        existing.setCustomerName(vo.getCustomerName());
        existing.setQuantity(vo.getQuantity());
        existing.setAmount(vo.getAmount());
        existing.setVehicleNumber(vo.getVehicleNumber());
        existing.setSupplierName(vo.getSupplierName());
        existing.setDeliveryDate(vo.getDeliveryDate());
        existing.setCreatedBy(vo.getCreatedBy());
        existing.setProductionStaff(vo.getProductionStaff());

        return this.updateById(existing);
    }

}




